package cn.edu.pku.controller;

import cn.edu.pku.entity.BookInfo;
import cn.edu.pku.service.BookInfoService;
import cn.edu.pku.vo.BookInfoResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * Created by intelligentdroid on 2017/5/9.
 */
@RestController
@Slf4j
@RequestMapping(value = "/book/info")
public class BookInfoController {
    @Autowired
    BookInfoService service;

    @RequestMapping(value = "/add")
    public BookInfoResult addBook(@RequestParam(value = "name") String name, @RequestParam(value = "isbn") String isbn, @RequestParam(value = "publisher", required = false) String publisher, @RequestParam(value = "author", required = false) String author, @RequestParam(value = "revision", required = false) String revision, @RequestParam(value = "language", required = false) String language, @RequestParam(value = "bookCategoryId", required = true) int bookCategoryId,
                                  @RequestParam(value = "price", required = false) double price, @RequestParam(value = "pageNum", required = false) int pageNum, @RequestParam(value = "bookSize", required = false) String bookSize, @RequestParam(value = "boughtTime", required = false) Date boughtTime, @RequestParam(value = "bookDes", required = false) String desc, @RequestParam(value = "icon", required = false) String icon) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setName(name);//书籍名字
        bookInfo.setIsbn(isbn);//ISBN
        bookInfo.setPublisher(publisher);//出版社名字
        bookInfo.setAuthor(author);//作者
        bookInfo.setRevision(revision);//版次
        bookInfo.setLanguage(language);//语种
        bookInfo.setBookCategoryId(bookCategoryId);//分类
        bookInfo.setPrice(price);//价格
        bookInfo.setPageNum(pageNum);//页数
        bookInfo.setBookSize(bookSize);//开本
        bookInfo.setBoughtTime(boughtTime);//购买时间
        bookInfo.setBookDes(desc);//简介
        bookInfo.setIcon(icon);//图片地址
        return service.addBook(bookInfo);
    }

    @RequestMapping(value = "/delete")
    public BookInfoResult delete(@RequestParam(value = "id") int id) {
        return service.deleteBook(id);
    }

    @RequestMapping(value = "/search")
    public BookInfoResult search(@RequestParam(value = "id") int id) {
        return service.search(id);
    }


    @RequestMapping(value = "/getall")
    public BookInfoResult getall() {
        return service.getAll();
    }


    @RequestMapping(value = "/update")
    public BookInfoResult update(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name, @RequestParam(value = "isbn") String isbn, @RequestParam(value = "publisher", required = false) String publisher, @RequestParam(value = "author", required = false) String author, @RequestParam(value = "revision", required = false) String revision, @RequestParam(value = "language", required = false) String language, @RequestParam(value = "bookCategoryId", required = true) int bookCategoryId,
                                 @RequestParam(value = "price", required = false) double price, @RequestParam(value = "pageNum", required = false) int pageNum, @RequestParam(value = "bookSize", required = false) String bookSize, @RequestParam(value = "boughtTime", required = false) Date boughtTime, @RequestParam(value = "bookDes", required = false) String desc, @RequestParam(value = "icon", required = false) String icon) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setId(id);
        bookInfo.setName(name);//书籍名字
        bookInfo.setIsbn(isbn);//ISBN
        bookInfo.setPublisher(publisher);//出版社名字
        bookInfo.setAuthor(author);//作者
        bookInfo.setRevision(revision);//版次
        bookInfo.setLanguage(language);//语种
        bookInfo.setBookCategoryId(bookCategoryId);//分类
        bookInfo.setPrice(price);//价格
        bookInfo.setPageNum(pageNum);//页数
        bookInfo.setBookSize(bookSize);//开本
        bookInfo.setBoughtTime(boughtTime);//购买时间
        bookInfo.setBookDes(desc);//简介
        bookInfo.setIcon(icon);//图片地址
        return service.updateBook(bookInfo);
    }


    @RequestMapping(value = "/upload/image")
    public BookInfoResult upload(MultipartFile file, @RequestParam(value = "bookid", required = false) int id, HttpServletRequest request) {
        BookInfoResult result = new BookInfoResult();
        if (file == null || file.isEmpty()) {// 判断文件是否为空
            result.setStatus(0);
            result.setMsg("请选择上传图片");
        } else {
            String imageDir = "upload";
            String filePathDir = request.getSession().getServletContext().getRealPath(File.separator) + imageDir + File.separator;
            try {
                // 文件保存路径
                if (!new File(filePathDir).exists()) {
                    new File(filePathDir).mkdirs();
                }
                String fileName = UUID.randomUUID().toString() + "." + file.getContentType();
                String filePath = filePathDir + fileName;
                file.transferTo(new File(filePath));
                String imgUrlPre = getServerPre(request);
                String imgUrl = imgUrlPre + File.separator + imageDir + File.separator + fileName;
                System.out.println("网络前缀" + imgUrlPre);
                System.out.println("图片网络地址" + imgUrl);
                result.setData(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }

            BookInfo bookInfo = service.selectByPrimaryKey(id);
            if (bookInfo != null) {//更新图书信息图片
                if (!StringUtils.isEmpty(bookInfo.getIcon())) {//说明之前有图片，删除之前的图片
                    String fileName = bookInfo.getIcon().substring(bookInfo.getIcon().lastIndexOf(File.separator));
                    File oldFile = new File(filePathDir+fileName);
                    if (oldFile.exists()){
                        oldFile.delete();
                    }
                }
            }
        }
        return result;
    }


    public String getServerPre(HttpServletRequest request) {
        //http://localhost:8012/upload/1234.jpg
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        String imgUrlPre = requestURL.replaceFirst(requestURI, "");
        return imgUrlPre;
    }
}
